package org.example.predicates;

import org.example.bean.Age;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
 * @Auther:Liu
 * @Testname:AgeRoutePredicateFactory
 * @Date:2025/9/15 16:30
 */
@Component
public class AgeRoutePredicateFactory extends AbstractRoutePredicateFactory<Age> {

    public AgeRoutePredicateFactory() {
        super(Age.class);
    }

    // 定义你的参数是否符合条件
    public Predicate<ServerWebExchange> apply(Age config) {
        int maxAge = config.getMax();
        int minAge = config.getMin();
        return exchange -> {
            // webflux  不是tomcat中的servlet
            ServerHttpRequest request = exchange.getRequest();
            String age = request.getQueryParams().get("age").get(0);
            int ageInt = Integer.parseInt(age);
            return ageInt >= minAge && ageInt <= maxAge;
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("min", "max");
    }
}
